<template>
  <div class="header-container">
    <div class="header-left flex-box">
      <el-icon class="icon" size="20" @click="handleClick">
        <Fold v-show="!isCollapse" />
        <Expand v-show="isCollapse" />
      </el-icon>
      <ul class="flex-box">
        <li v-for="(item, index) in selectMenu" :key="item.path" :class="{ selected: route.path === item.path }"
          class="tab flex-box">
          <el-icon>
            <component size="20" :is="item.icon" />
          </el-icon>
          <router-link class="text flex-box" :to="item.path" @click="updateSelectMenu(item)">
            {{ item.name }}
          </router-link>
          <el-icon class="close" size="15" @click="closeTab(item, index)">
            <Close />
          </el-icon>
        </li>
      </ul>
    </div>
    <div class="header-right flex-box">
      <el-dropdown @command="handleCommand">
        <span class="el-dropdown-link flex-box">
          <el-avatar :size="40" :src="userInfo.avatar"/>
          <p class="user-name">{{ userInfo.name }}</p>
        </span>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item command="cancel">退出</el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </div>
  </div>
</template>

<script setup>
import { computed } from "vue";
import { useStore } from "vuex";
import { useRoute, useRouter } from "vue-router";

const store = useStore();
const router = useRouter();
const route = useRoute();

const userInfo = JSON.parse(localStorage.getItem('pz_userInfo'))

const handleClick = () => {
  store.commit("collapseMenu");
}
const closeTab = (item, index) => {
  store.commit('removeMenu', item)
  //删除的不是当前页
  if (route.path !== item.path) {
    return
  }
  const selectMenuData = selectMenu.value
  // 是否是最后一项
  if (index === selectMenuData.length) {
    // 只剩一个tag
    if (selectMenuData.length === 0) {
      router.push('/')
    }
    else {
      router.push({ path: selectMenuData[index - 1].path })
    }
  }
  else {
    router.push({ path: selectMenuData[index].path })
  }
}

const updateSelectMenu = (item) => {
  console.log('updateSelectMenu')
  // store.commit('updateSelectMenu', item.)
}

const isCollapse = computed(() => store.state.Menu.isCollapse);
const selectMenu = computed(() => store.state.Menu.selectMenu);

const handleCommand=(command)=>{
  if(command==='cancel'){
    localStorage.removeItem('pz_token')
    localStorage.removeItem('pz_userInfo')
    localStorage.removeItem('pz_v3pz')

    window.location.href = window.location.origin
  }
}
</script>

<style lang="scss" scoped></style>
